﻿#include "const.h"
#include "ConfigManager.h"
#include "RedisManager.h"
#include "StatusServiceImplement.h"

#include <grpc++/grpc++.h>

void runServer()
{
    auto& cfg = ConfigManager::getInstance();
    std::string server_address(cfg["StatusServer"]["Host"] + ":" + cfg["StatusServer"]["Port"]);
    StatusServiceImplement service;

    grpc::ServerBuilder builder;
    // 开启监听端口和添加服务
    builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
    builder.RegisterService(&service);

    // 创建并启动grpc服务器
    std::unique_ptr<grpc::Server> server(builder.BuildAndStart());
    std::cout << "Server listening on " << server_address << std::endl;

    boost::asio::io_context ioc;
    boost::asio::signal_set signals(ioc, SIGINT, SIGTERM);

    // 设置异步等待的信号回调处理
    signals.async_wait([&server, &ioc](const boost::system::error_code& err, int signal_number) {
        if (!err) {
            std::cout << "Shutting down server......" << std::endl;
            server->Shutdown(); // 优雅地关闭服务器
            ioc.stop(); // 停止io_context
        }
    });

    // 在单独的线程中运行io_context
    std::thread([&ioc]() { ioc.run(); }).detach();

    // 等待服务器关闭
    server->Wait();
}


int main(int argc, char* argv[])
{
    try {
        std::cout << "this is StatusServer......" << std::endl;
        runServer();
        RedisManager::getInstance()->close();
    }
    catch (std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
}
